/**
 * 路由配置
 */
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

// 布局组件
const Layout = () => import('@/layout/index.vue')

// 页面组件
const Login = () => import('@/views/login/index.vue')
const Register = () => import('@/views/register/index.vue')
const Dashboard = () => import('@/views/dashboard/index.vue')

// 题库管理
const QuestionBankList = () => import('@/views/questions/bank-list.vue')
const QuestionBankDetail = () => import('@/views/questions/bank-detail.vue')
const QuestionList = () => import('@/views/questions/question-list.vue')
const QuestionEditor = () => import('@/views/questions/question-editor.vue')

// 考试管理
const ExamList = () => import('@/views/examinations/exam-list.vue')
const ExamDetail = () => import('@/views/examinations/exam-detail.vue')
const ExamCreate = () => import('@/views/examinations/exam-create.vue')
const ExamTaking = () => import('@/views/examinations/exam-taking.vue')
const ExamMonitor = () => import('@/views/examinations/exam-monitor.vue')
const ExamResult = () => import('@/views/examinations/exam-result.vue')

// 试卷管理
const PaperTemplateList = () => import('@/views/exam-paper/template-list.vue')
const PaperTemplateEditor = () => import('@/views/exam-paper/template-editor.vue')
const PaperList = () => import('@/views/exam-paper/paper-list.vue')
const PaperDetail = () => import('@/views/exam-paper/paper-detail.vue')
const PaperEditor = () => import('@/views/exam-paper/paper-editor.vue')
const PaperPreview = () => import('@/views/exam-paper/paper-preview.vue')

// 成绩管理
const GradeSheetList = () => import('@/views/grading/sheet-list.vue')
const GradeSheetDetail = () => import('@/views/grading/sheet-detail.vue')
const GradeSheetCreate = () => import('@/views/grading/sheet-create.vue')
const GradeList = () => import('@/views/grading/grade-list.vue')
const GradeAnalysis = () => import('@/views/grading/grade-analysis.vue')
const GradeAppeal = () => import('@/views/grading/grade-appeal.vue')

// 系统管理
const UserManagement = () => import('@/views/system/users.vue')
const SystemSettings = () => import('@/views/system/settings.vue')
const SystemLogs = () => import('@/views/system/logs.vue')

// 个人中心
const Profile = () => import('@/views/profile/index.vue')
const ChangePassword = () => import('@/views/profile/change-password.vue')
const MyResults = () => import('@/views/profile/my-results.vue')

// 错误页面
const NotFound = () => import('@/views/error/404.vue')
const ServerError = () => import('@/views/error/500.vue')

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录',
      requiresAuth: false,
      hideLayout: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: {
      title: '注册',
      requiresAuth: false,
      hideLayout: true
    }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: {
          title: '控制台',
          icon: 'dashboard',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/questions',
    component: Layout,
    redirect: '/questions/banks',
    meta: {
      title: '题库管理',
      icon: 'question',
      requiresAuth: true
    },
    children: [
      {
        path: 'banks',
        name: 'QuestionBankList',
        component: QuestionBankList,
        meta: {
          title: '题库列表',
          icon: 'list'
        }
      },
      {
        path: 'banks/:id',
        name: 'QuestionBankDetail',
        component: QuestionBankDetail,
        meta: {
          title: '题库详情',
          hideInMenu: true
        }
      },
      {
        path: 'questions',
        name: 'QuestionList',
        component: QuestionList,
        meta: {
          title: '题目列表',
          icon: 'document'
        }
      },
      {
        path: 'questions/create',
        name: 'QuestionCreate',
        component: QuestionEditor,
        meta: {
          title: '创建题目',
          hideInMenu: true
        }
      },
      {
        path: 'questions/:id/edit',
        name: 'QuestionEdit',
        component: QuestionEditor,
        meta: {
          title: '编辑题目',
          hideInMenu: true
        }
      }
    ]
  },
  {
    path: '/examinations',
    component: Layout,
    redirect: '/examinations/list',
    meta: {
      title: '考试管理',
      icon: 'exam',
      requiresAuth: true
    },
    children: [
      {
        path: 'list',
        name: 'ExamList',
        component: ExamList,
        meta: {
          title: '考试列表',
          icon: 'list'
        }
      },
      {
        path: 'create',
        name: 'ExamCreate',
        component: ExamCreate,
        meta: {
          title: '创建考试',
          icon: 'plus'
        }
      },
      {
        path: ':id',
        name: 'ExamDetail',
        component: ExamDetail,
        meta: {
          title: '考试详情',
          hideInMenu: true
        }
      },
      {
        path: ':id/take',
        name: 'ExamTaking',
        component: ExamTaking,
        meta: {
          title: '参加考试',
          hideInMenu: true
        }
      },
      {
        path: ':id/monitor',
        name: 'ExamMonitor',
        component: ExamMonitor,
        meta: {
          title: '监考',
          hideInMenu: true,
          roles: ['teacher', 'admin']
        }
      },
      {
        path: ':id/result',
        name: 'ExamResult',
        component: ExamResult,
        meta: {
          title: '考试结果',
          hideInMenu: true
        }
      }
    ]
  },
  {
    path: '/papers',
    component: Layout,
    redirect: '/papers/templates',
    meta: {
      title: '试卷管理',
      icon: 'document',
      requiresAuth: true
    },
    children: [
      {
        path: 'templates',
        name: 'PaperTemplateList',
        component: PaperTemplateList,
        meta: {
          title: '试卷模板',
          icon: 'template'
        }
      },
      {
        path: 'templates/create',
        name: 'PaperTemplateCreate',
        component: PaperTemplateEditor,
        meta: {
          title: '创建模板',
          hideInMenu: true
        }
      },
      {
        path: 'templates/:id/edit',
        name: 'PaperTemplateEdit',
        component: PaperTemplateEditor,
        meta: {
          title: '编辑模板',
          hideInMenu: true
        }
      },
      {
        path: 'list',
        name: 'PaperList',
        component: PaperList,
        meta: {
          title: '试卷列表',
          icon: 'list'
        }
      },
      {
        path: 'create',
        name: 'PaperCreate',
        component: PaperEditor,
        meta: {
          title: '创建试卷',
          hideInMenu: true
        }
      },
      {
        path: ':id',
        name: 'PaperDetail',
        component: PaperDetail,
        meta: {
          title: '试卷详情',
          hideInMenu: true
        }
      },
      {
        path: ':id/edit',
        name: 'PaperEdit',
        component: PaperEditor,
        meta: {
          title: '编辑试卷',
          hideInMenu: true
        }
      },
      {
        path: ':id/preview',
        name: 'PaperPreview',
        component: PaperPreview,
        meta: {
          title: '预览试卷',
          hideInMenu: true
        }
      }
    ]
  },
  {
    path: '/grading',
    component: Layout,
    redirect: '/grading/sheets',
    meta: {
      title: '成绩管理',
      icon: 'grade',
      requiresAuth: true
    },
    children: [
      {
        path: 'sheets',
        name: 'GradeSheetList',
        component: GradeSheetList,
        meta: {
          title: '成绩单',
          icon: 'list'
        }
      },
      {
        path: 'sheets/create',
        name: 'GradeSheetCreate',
        component: GradeSheetCreate,
        meta: {
          title: '创建成绩单',
          hideInMenu: true
        }
      },
      {
        path: 'sheets/:id',
        name: 'GradeSheetDetail',
        component: GradeSheetDetail,
        meta: {
          title: '成绩单详情',
          hideInMenu: true
        }
      },
      {
        path: 'grades',
        name: 'GradeList',
        component: GradeList,
        meta: {
          title: '成绩列表',
          icon: 'grade'
        }
      },
      {
        path: 'analysis',
        name: 'GradeAnalysis',
        component: GradeAnalysis,
        meta: {
          title: '成绩分析',
          icon: 'chart'
        }
      },
      {
        path: 'appeals',
        name: 'GradeAppeal',
        component: GradeAppeal,
        meta: {
          title: '成绩申诉',
          icon: 'appeal'
        }
      }
    ]
  },
  {
    path: '/system',
    component: Layout,
    redirect: '/system/users',
    meta: {
      title: '系统管理',
      icon: 'setting',
      requiresAuth: true,
      roles: ['admin']
    },
    children: [
      {
        path: 'users',
        name: 'UserManagement',
        component: UserManagement,
        meta: {
          title: '用户管理',
          icon: 'user'
        }
      },
      {
        path: 'settings',
        name: 'SystemSettings',
        component: SystemSettings,
        meta: {
          title: '系统设置',
          icon: 'setting'
        }
      },
      {
        path: 'logs',
        name: 'SystemLogs',
        component: SystemLogs,
        meta: {
          title: '系统日志',
          icon: 'log'
        }
      }
    ]
  },
  {
    path: '/profile',
    component: Layout,
    redirect: '/profile/index',
    meta: {
      title: '个人中心',
      icon: 'user',
      requiresAuth: true
    },
    children: [
      {
        path: 'index',
        name: 'Profile',
        component: Profile,
        meta: {
          title: '个人信息',
          icon: 'user'
        }
      },
      {
        path: 'password',
        name: 'ChangePassword',
        component: ChangePassword,
        meta: {
          title: '修改密码',
          icon: 'lock'
        }
      },
      {
        path: 'results',
        name: 'MyResults',
        component: MyResults,
        meta: {
          title: '我的成绩',
          icon: 'grade'
        }
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: '页面不存在',
      hideLayout: true
    }
  },
  {
    path: '/500',
    name: 'ServerError',
    component: ServerError,
    meta: {
      title: '服务器错误',
      hideLayout: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    return { top: 0 }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - AI-SOES` : 'AI-SOES 智能在线考试系统'

  // 检查是否需要认证
  if (to.meta.requiresAuth !== false) {
    if (!authStore.isAuthenticated) {
      next({ name: 'Login', query: { redirect: to.fullPath } })
      return
    }
  }

  // 检查角色权限
  if (to.meta.roles && Array.isArray(to.meta.roles)) {
    const userRole = authStore.user?.role
    if (!userRole || !to.meta.roles.includes(userRole)) {
      next({ name: 'Dashboard' })
      return
    }
  }

  // 如果已登录访问登录/注册页面，重定向到首页
  if (authStore.isAuthenticated && (to.name === 'Login' || to.name === 'Register')) {
    next({ name: 'Dashboard' })
    return
  }

  next()
})

export default router